package com.gmrz.uap.tenant;

import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.common.DbConst;
import com.gmrz.uap.common.UAPSSOHelper;
import com.gmrz.uap.model.Dict;
import com.gmrz.uap.model.Tenant;
import com.gmrz.uap.model.TenantConfig;
import com.gmrz.uap.model.User;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.util.Identities;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

public class TenantController extends ControllerSupport {
    private static final String UAF_APPLICATIOIN_ID = "uaf.application.id";
    private static final Logger LOG = LogManager.getLogger(TenantController.class);
    public static String[] tenantConfigENameArray = new String[]{"uaf.uvs.match", "uaf.exact.match", "uaf.application.id", "webauthn.authenticator.selection.criteria.authenticator.attachment",
            "webauthn.authenticator.selection.criteria.require.residentkey",
            "webauthn.authenticator.selection.criteria.user.verification",
            "webauthn.auth.anonymous",
            "webauthn.auth.strictmode"};

    public static String[] webtenantConfigENameArray = new String[]{"webauthn.authenticator.selection.criteria.authenticator.attachment",
            "webauthn.authenticator.selection.criteria.require.residentkey",
            "webauthn.authenticator.selection.criteria.user.verification"};
    /**
     * 渠道管理主页面
     */
    @Before(ResourceInterceptor.class)
    public void index() {
    }

    /**
     * 根据前台发过来的参数进行查询，可以进行分页，排序
     */
    public void list() {

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, SystemConst.DEFAULT_ORDERBY_CREATETS);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Tenant tenant = getModel(Tenant.class);

        User user = UAPSSOHelper.getUserByUapSessionId(getRequest());
        user = User.dao.findById(user.getUserId());
        if (StringUtils.isNotBlank(user.getTenantId())) {
            tenant.put("tenantIds", user.getTenantId());
        }

        Page<Tenant> descPage = TenantService.me.findTenantListForPaginate(tenant, page, rows, sort, order);

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    /**
     * 获取所有的渠道信息
     */
    public void listAll() {
        List<Tenant> tenants = TenantService.me.getAllTenants();
        render(responseJsonRender(tenants));
    }

    /**
     * 增加页面跳转
     */

    public void add() {
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 保存数据信息
     */
    public void save() {

        Tenant tenant = getModel(Tenant.class);

        if (null == tenant) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        tenant.setStatus(1);
        tenant.setTenantId(tenant.getTenantId().trim());

        List<Tenant> all = TenantService.me.getAllTenants();

        List<String> listnames = new ArrayList<String>();

        for (Tenant t : all) {
            listnames.add(t.getTenantId());
        }

        if (!listnames.contains(tenant.getTenantId())) {

            flag = TenantService.me.save(tenant);

            if (flag) {
                message = getRes().get("system.validator.add.success");
            } else {
                message = getRes().get("system.validator.add.error");
            }
        } else {
            message = getRes().get("system.tenant.add.exist");
        }


        if (flag) {
            List<Tenant> tenants = TenantService.me.getByEName(tenantConfigENameArray);
            TenantConfig tenantConfig;
            for (Tenant tenantTmp : tenants) {
                if("uaf.application.id".equals(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_ENAME))){
                    //List<Dict> transTypeList = DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_TRANS_TYPE_ID);
                    List<Dict> transTypeList = new ArrayList<Dict>();
                    Dict dict0 = new Dict();
                    dict0.setDictName("登录");
                    dict0.setDictText("00");
                    transTypeList.add(dict0);
                    Dict dict1 = new Dict();
                    dict1.setDictName("支付");
                    dict1.setDictText("01");
                    transTypeList.add(dict1);
                    Dict dict2 = new Dict();
                    dict2.setDictName("验签");
                    dict2.setDictText("02");
                    transTypeList.add(dict2);
                    for(Dict dict : transTypeList) {

                        tenantConfig = new TenantConfig();
                        tenantConfig.setTcId(Identities.uuid2());
                        tenantConfig.setTenantId(tenant.getTenantId());
                        tenantConfig.setConfigCname(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_CNAME)+dict.getDictText());
                        tenantConfig.setConfigEname(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_ENAME));
                        tenantConfig.setConfigValue(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_VALUE));
                        tenantConfig.setDataType(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_DATA_TYPE));
                        tenantConfig.setRegex(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_REGEX));
                        tenantConfig.setErrorMsg(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_ERROR_MSG));
                        if (StrKit.equals(UAF_APPLICATIOIN_ID, tenantConfig.getConfigEname())) {
                            tenantConfig.setTransType(dict.getDictText());
                        }
                        flag = tenantConfig.save();
                        if (!flag) message = "增加渠道配置信息出现异常";
                    }
                }else {
                    tenantConfig = new TenantConfig();
                    tenantConfig.setTcId(Identities.uuid2());
                    tenantConfig.setTenantId(tenant.getTenantId());
                    tenantConfig.setConfigCname(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_CNAME));
                    tenantConfig.setConfigEname(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_ENAME));
                    tenantConfig.setConfigValue(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_CONFIG_VALUE));
                    tenantConfig.setDataType(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_DATA_TYPE));
                    tenantConfig.setRegex(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_REGEX));
                    tenantConfig.setErrorMsg(tenantTmp.getStr(DbConst.TABLE_UAS_CONFIG_COLUMN_ERROR_MSG));
                    flag = tenantConfig.save();
                    if (!flag) message = "增加渠道配置信息出现异常";
                }
            }


            User user = UAPSSOHelper.getUserByUapSessionId(getRequest());
            user = User.dao.findById(user.getUserId());
            if (StringUtils.isNotBlank(user.getTenantId())) {
                user.setTenantId(user.getTenantId() + "," + tenant.getTenantId());
                flag = user.update();
                if (!flag) message = "修改用户渠道信息出现异常";
            }
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("添加渠道信息", tenant.getTenantId(), flag, message, getRequest());


        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 编辑页面跳转
     */
    public void edit() {
        Tenant tenant = Tenant.dao.findById(getPara());
        setAttr("tenant", tenant);
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 修改数据信息
     */
    public void update() {
        Tenant tenant = getModel(Tenant.class);

        if (null == tenant) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        //默认渠道不能进行修改
        if (StringUtils.equals("default", tenant.getTenantId().trim())) {
            message = getRes().get("tenant.validator.defaulterr");
        } else {

            flag = TenantService.me.update(tenant);

            if (flag) {
                message = getRes().get("system.validator.edit.success");
            } else {
                message = getRes().get("system.validator.edit.error");
            }
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("更新渠道信息", tenant.getTenantId(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 根据ID删除数据信息，可以同时删除多个，数据使用逗号(,)隔开
     */
    public void remove() {

        String ids = getPara(0);
        String tenants = getPara(1);

        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        getModel(Tenant.class);

        flag = TenantService.me.remove(ids);

        if (flag) {
            message = getRes().get("system.validator.remove.success");
        } else {
            message = getRes().get("system.validator.remove.error");
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(" 删除渠道信息", tenants, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 判断访问地址是否存在
     */
    public void exist() {
        flag = TenantService.me.exist(getPara("tenant.form.tenantid"));
        render(responseJsonRender(flag));
    }

}
